package com.easyOrder.service.impl;

/**
 * Created by liutao on 2017/7/20.
 */

import com.easyOrder.core.exception.api.ArgumentsIncorrectException;
import com.easyOrder.query.SequenceQuery;
import com.easyOrder.service.ISequenceService;
import com.easyOrder.service.enums.SeqType;
import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class SequenceBuilder implements ISequenceService {

    @Autowired
    private ApplicationContext applicationContext;

    private final static SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");

    @Override
    public Long newKey(SeqType seqType) {
        Long key = (Long) getSqlSession().selectOne("data.__nextValue", seqType.getValue());
        if (key.equals(-1L)) {
            throw new ArgumentsIncorrectException(MessageFormat.format("序列: {0} 在__Sequence中不存在", seqType.getValue()));
        }
        return key;
    }

    @Override
    public List<Long> newKeys(SeqType seqType, int size) {
        SequenceQuery query = new SequenceQuery();
        query.setName(seqType.getValue());
        query.setSize(size);
        Long key = (Long) getSqlSession().selectOne("data.__nextValues", query);
        if (key.equals(-1L)) {
            throw new ArgumentsIncorrectException(MessageFormat.format("序列: {0} 在__Sequence中不存在", seqType.getValue()));
        } else {
            List<Long> result = Lists.newArrayList();
            for (int i = 0; i < size; i++) {
                result.add(key + i);
            }
            return result;
        }

    }

    private SqlSession getSqlSession() {
        return (SqlSession) applicationContext.getBean("sqlSession");
    }

    @Override
    public String newCode(SeqType seqTypes, Integer id) {
        return build(seqTypes, Long.valueOf(id));
    }

    @Override
    public String newCode(SeqType seqTypes, Long id) {
        return build(seqTypes, id);
    }

    private String build(SeqType seqTypes, Long id) {
        StringBuilder seqNumber = new StringBuilder();
        seqNumber.append(seqTypes.getCodePrefix()).append(getCurrentTime()).append(fillZero(id + "", 4));
        return seqNumber.toString();
    }

    private String fillZero(String str, int size) {
        return StringUtils.leftPad(str, size, '0');
    }

    private String getCurrentTime() {
        return sdf.format(new Date(System.currentTimeMillis()));
    }
}

